﻿@{
    Layout = null;
    string orderStatusListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.OrderStatusList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
    string stockInOutStatusListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.StockInTypeList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
    string transferTypeListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.TransferTypeList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>调拨订单列表</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
    <style>
        #tableBlock {
            margin: 0 auto;
            width: 1700px;
            padding-bottom: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
            padding: 1%;
        }

            #tableBlock label {
                font-size: 24px;
            }

        .formTableInput, .formTableSelect {
            display: inline-block;
            width: 180px;
        }

        .buttonBlock {
            height: 40px;
            width: 100%;
            padding-top: 10px;
            padding-left: 20px;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
        }

        .audit-textarea {
            margin-top: 15px;
            width: 100%;
        }

        .operate-btn {
            margin-right: 8px;
        }

        .btnAndTable {
            margin: 0 auto;
            margin-left: 50px;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout"
         data-order-status-list="@orderStatusListJson"
         data-stock-in-out-status-list="@stockInOutStatusListJson"
         data-transfer-type-list="@transferTypeListJson">
        <div id="tableBlock">
            <form>
                <table width="1700px" height="80px">
                    <tbody>
                        <tr style="background-color: #fff;">
                            <td height="40px" width="200px">
                                <span>调拨单号</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-input v-model="transferOrderNoInput" class="formTableInput" placeholder="请输入"></el-input>
                            </td>
                            <td height="40px" width="200px">
                                <span>单据状态</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedStatus" class="formTableSelect" placeholder="请选择单据状态">
                                    <el-option v-for="(status, index) in stockInStatusList" :key="index" :label="status.Name" :value="status.Code"></el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="200px">
                                <span>出入库状态</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedInOutStatus" class="formTableSelect" placeholder="请选择状态" clearable>
                                    <el-option v-for="(status, index) in stockInOutStatusList" :key="index" :label="status.Name" :value="status.Code"></el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="280px">
                                <span>调拨申请日</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-date-picker id="dateRangePicker" class="formTableInput" type="daterange" range-separator="至"
                                                start-placeholder="开始时间" end-placeholder="结束时间" :size="size"
                                                v-model="dateRange" value-format="YYYY-MM-DD"></el-date-picker>
                            </td>
                            <td height="40px" width="160px">
                                <el-button type="reset" v-on:click="resetForm">重置</el-button>&nbsp;
                                <el-button type="primary" v-on:click="searchTable">查询</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>
            <div class="btnAndTable">
                <div class="buttonBlock">
                    <el-button type="primary" v-on:click="addOrder">新增</el-button>&nbsp;
                    <el-button type="danger" v-on:click="deleteOrder">删除</el-button>&nbsp;
                    <el-button type="default" v-on:click="copyOrder">复制</el-button>&nbsp;
                    <el-button type="danger" v-on:click="openAuditModal">审核</el-button>&nbsp;
                    <el-button type="danger" v-on:click="cancleCheck">撤销</el-button>&nbsp;
                    <el-button type="default" v-on:click="exportTable">导出</el-button>&nbsp;
                    <el-button type="success" v-on:click="refrushTable">刷新</el-button>&nbsp;
                </div>
                <!-- 表格：绑定格式化函数 -->
                <el-table :data="paginatedData" style="width: 1600px; margin-top: 10px"
                          v-on:selection-change="handleSelectionChange" ref="multipleTable" stripe>
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed label="调拨单号" width="150">
                        <template #default="scope">
                            <span style="color: #10b981; cursor: pointer;" v-on:click="jumpToDetail(scope.row)">{{ scope.row.transferOrderNo }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed prop="orderStatus" label="单据状态" width="100" :formatter="formatStatusColumn"></el-table-column>
                    <el-table-column fixed prop="operatorDate" label="调拨申请日期" width="150" :formatter="formatDate"></el-table-column>
                    <!-- 调拨类型：绑定formatTransferTypeColumn -->
                    <el-table-column prop="transferType" label="调拨类型" width="120" :formatter="formatTransferTypeColumn"></el-table-column>
                    <el-table-column prop="transferOutWarehouse" label="调出仓库" width="120"></el-table-column>
                    <el-table-column prop="transferInWarehouse" label="调入仓库" width="120"></el-table-column>
                    <!-- 出库状态：绑定formatInOutStatusColumn -->
                    <el-table-column prop="outbound" label="出库状态" width="120" :formatter="formatInOutStatusColumn"></el-table-column>
                    <!-- 入库状态：绑定formatInOutStatusColumn -->
                    <el-table-column prop="inbound" label="入库状态" width="120" :formatter="formatInOutStatusColumn"></el-table-column>
                    <el-table-column prop="allTransferQuantity" label="调拨数量(吨)" width="120" :formatter="formatNumber"></el-table-column>
                    <el-table-column prop="allTransferAmount" label="调拨金额(元)" width="120" :formatter="formatNumber"></el-table-column>
                    <el-table-column prop="operatorBy" label="经办人" width="120"></el-table-column>
                    <el-table-column prop="allGoodsName" label="调拨货品" width="120" :formatter="formatGoodsName"></el-table-column>
                    <el-table-column prop="createBy" label="制单人" width="120"></el-table-column>
                    <el-table-column prop="orgName" label="所在部门" width="120"></el-table-column>
                    <el-table-column prop="createTime" label="制单时间" width="120" :formatter="formatDate"></el-table-column>
                    <el-table-column prop="auditorBy" label="审核人" width="120"></el-table-column>
                    <el-table-column prop="auditorTime" label="审核时间" width="120" :formatter="formatDate"></el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="180">
                        <template #default="scope">
                            <el-button v-if="getStatusText(scope.row.orderStatus) === '草稿' || getStatusText(scope.row.orderStatus) === '待审核'"
                                       class="operate-btn" link type="primary" size="default" v-on:click="handleEdit(scope.row)">编辑</el-button>
                            <el-button v-if="getStatusText(scope.row.orderStatus) === '草稿' || getStatusText(scope.row.orderStatus) === '待审核'"
                                       class="operate-btn" link type="danger" size="default" v-on:click="deleteSingleOrder(scope.row)">删除</el-button>
                            <el-button v-if="getStatusText(scope.row.orderStatus) === '驳回'"
                                       class="operate-btn" link type="primary" size="default" v-on:click="handleEdit(scope.row)">编辑</el-button>
                            <el-button v-if="getStatusText(scope.row.orderStatus) === '驳回'"
                                       class="operate-btn" link type="warning" size="default" v-on:click="handleRejectCancel(scope.row)">撤销</el-button>
                            <el-button v-if="getStatusText(scope.row.orderStatus) === '未入库'"
                                       class="operate-btn" link type="warning" size="default" v-on:click="handleRejectCancel(scope.row)">撤销</el-button>
                            <span v-if="getStatusText(scope.row.orderStatus) === '部分入库' || getStatusText(scope.row.orderStatus) === '已完成'">-</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                               :page-sizes="[10, 20, 50, 100]" :total="total"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handleSizeChange" v-on:current-change="handleCurrentChange"></el-pagination>
            </div>
        </div>
        <!-- 审核模态框 -->
        <el-dialog title="订单审核" v-model="isAuditModalOpen" width="500px" :before-close="handleAuditModalClose">
            <div class="audit-content">
                <!-- 显示选中的调拨单数量（已移除 .value） -->
                <div style="margin-bottom: 10px; color: #666;">
                    当前选中 {{ selectedRowCount }} 条单据
                </div>
                <el-radio-group v-model="selectedAuditResult" required>
                    <el-radio label="pass">通过</el-radio>
                    <el-radio label="reject">驳回</el-radio>
                </el-radio-group>
                <el-input class="audit-textarea" type="textarea" v-model="auditOpinion"
                          placeholder="请输入审核意见（驳回时必填）" :rows="4" :maxlength="200" show-word-limit></el-input>
            </div>
            <template #footer>
                <el-button v-on:click="isAuditModalOpen = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmAudit">确认审核</el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted, nextTick,computed } = Vue;
        const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;
        const app = createApp({
            setup() {
                // 1. 筛选条件变量
                const orderNoInput = ref('');
                const transferOrderNoInput = ref('');
                const selectedStatus = ref('');
                const selectedInOutStatus = ref('');
                const dateRange = ref([]);
                const size = ref('default');

                // 2. 表格与分页变量
                const allTableData = ref([]);
                const paginatedData = ref([]);
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = ref(0);
                const selectedRows = ref([]);
                const multipleTable = ref(null);

                // 3. 数据字典变量
                const stockInStatusList = ref([]);
                const stockInOutStatusList = ref([]);
                const transferTypeList = ref([]);

                // 4. 审核模态框变量
                const isAuditModalOpen = ref(false);
                const selectedAuditResult = ref('pass'); // 默认选中“通过”
                const auditOpinion = ref('');
                const getCurrentUserId = () => {
                    const userStr = sessionStorage.getItem('YH');
                    if (!userStr) {
                        ElMessage.warning('未检测到登录状态，请重新登录');
                        return '';
                    }
                    try {
                        const userObj = JSON.parse(userStr);
                        const userId = userObj?.id?.toString() || '';
                        if (!userId) ElMessage.warning('用户信息不完整，请重新登录');
                        return userId;
                    } catch (error) {
                        console.error('解析用户信息失败：', error);
                        ElMessage.error('用户信息异常，请重新登录');
                        return '';
                    }
                };
                // 当前登录用户ID（替换原固定值）
                const currentUserId = ref(getCurrentUserId());

                // 初始化数据字典
                const initDictData = () => {
                    try {
                        const orderStatusStr = document.getElementById('app').dataset.orderStatusList || '[]';
                        const parsedOrderStatus = JSON.parse(decodeURIComponent(orderStatusStr));
                        stockInStatusList.value = Array.isArray(parsedOrderStatus) ? parsedOrderStatus : [];

                        const stockInOutStatusStr = document.getElementById('app').dataset.stockInOutStatusList || '[]';
                        const parsedInOutStatus = JSON.parse(decodeURIComponent(stockInOutStatusStr));
                        stockInOutStatusList.value = Array.isArray(parsedInOutStatus) ? parsedInOutStatus : [];

                        const transferTypeStr = document.getElementById('app').dataset.transferTypeList || '[]';
                        const parsedTransferType = JSON.parse(decodeURIComponent(transferTypeStr));
                        transferTypeList.value = Array.isArray(parsedTransferType) ? parsedTransferType : [];

                        loadTableData();
                    } catch (e) {
                        console.error('数据字典解析失败：', e);
                        ElMessage.error('页面初始化异常，请刷新重试');
                    }
                };

                // 5. 加载表格数据
                const loadTableData = async () => {
                    try {
                        const queryParams = {
                            transferOrderNo: transferOrderNoInput.value.trim() || '',
                            orderStatus: selectedStatus.value || '',
                            inOutStatus: selectedInOutStatus.value || '',
                            startDate: dateRange.value[0] || '',
                            endDate: dateRange.value[1] || '',
                            page: currentPage.value,
                            pageSize: pageSize.value
                        };

                        const res = await axios.get('/WhTransfer/GetAllTransferInfo', { params: queryParams });
                        allTableData.value = Array.isArray(res.data) ? res.data : [];
                        total.value = allTableData.value.length;
                        paginateTableData();

                        if (allTableData.value.length === 0) {
                            ElMessage.info('未查询到符合条件的调拨单数据');
                        }
                    } catch (error) {
                        console.error('调拨单数据加载失败：', error);
                        ElMessage.error('网络异常，无法加载调拨单数据');
                        allTableData.value = [];
                        paginatedData.value = [];
                        total.value = 0;
                    }
                };

                // 6. 分页处理
                const paginateTableData = () => {
                    const startIndex = (currentPage.value - 1) * pageSize.value;
                    const endIndex = startIndex + pageSize.value;
                    paginatedData.value = allTableData.value.slice(startIndex, endIndex);
                };

                                // 7. 格式化函数
                const formatDate = (row, column, cellValue) => {
                    if (!cellValue) return ''; // 空值直接返回空字符串
                    const date = new Date(cellValue);
                    if (isNaN(date.getTime()) || date.getTime() < 100000000000) {
                        return '';
                    }
                    return date.toLocaleDateString();
                };

                const formatNumber = (row, column, cellValue) => {
                    if (cellValue == null || isNaN(cellValue)) return '0.00';
                    return Number(cellValue).toFixed(2);
                };

                const formatGoodsName = (row, column, cellValue) => {
                    if (!cellValue) return '-';
                    return cellValue.length <= 10 ? cellValue : cellValue.slice(0, 10) + '...';
                };

                // 单据状态文本转换
                const getStatusText = (statusCode) => {
                    if (!statusCode) return '-';
                    const orderStatusItem = stockInStatusList.value.find(
                        item => String(item.Code) === String(statusCode)
                    );
                    if (orderStatusItem) return orderStatusItem.Name;
                    const inOutStatusItem = stockInOutStatusList.value.find(
                        item => String(item.Code) === String(statusCode)
                    );
                    return inOutStatusItem ? inOutStatusItem.Name : statusCode;
                };

                // 调拨类型文本转换
                const getTransferTypeText = (typeCode) => {
                    if (!typeCode) return '-';
                    const typeItem = transferTypeList.value.find(item => String(item.Code) === String(typeCode));
                    return typeItem ? typeItem.Name : typeCode;
                };

                // 出入库状态文本转换
                const getInOutStatusText = (statusCode) => {
                    if (!statusCode) return '-';
                    const statusItem = stockInOutStatusList.value.find(item => String(item.Code) === String(statusCode));
                    return statusItem ? statusItem.Name : statusCode;
                };

                // 表格列格式化函数
                const formatStatusColumn = (row, column, cellValue) => {
                    return getStatusText(cellValue);
                };

                const formatTransferTypeColumn = (row, column, cellValue) => {
                    return getTransferTypeText(cellValue);
                };

                const formatInOutStatusColumn = (row, column, cellValue) => {
                    return getInOutStatusText(cellValue);
                };

                // 8. 筛选与重置
                const searchTable = () => {
                    currentPage.value = 1;
                    // 构建与后端实体匹配的查询参数
                    const queryParams = {
                        orderNo: transferOrderNoInput.value.trim() || '', // 对应后端 orderNo
                        OrderStatus: selectedStatus.value || '', // 对应后端 OrderStatus
                        InboundOrOutBound: selectedInOutStatus.value || '', // 对应后端 InboundOrOutBound
                    };
                    // 处理日期格式：仅在用户选择了日期时才传递对应的字段
                    if (dateRange.value && dateRange.value.length === 2) {
                        queryParams.StartTime = new Date(dateRange.value[0]);
                        queryParams.EndTime = new Date(dateRange.value[1]);
                    }

                    // 执行查询
                    const loadData = async () => {
                        try {
                            const res = await axios.post('/WhTransfer/GetTransferWithSth', queryParams, {
                                headers: { 'Content-Type': 'application/json' }
                            });
                            allTableData.value = Array.isArray(res.data) ? res.data : [];
                            total.value = allTableData.value.length;
                            paginateTableData();

                            if (allTableData.value.length === 0) {
                                ElMessage.info('未查询到符合条件的调拨单数据');
                            }
                        } catch (error) {
                            console.error('查询失败：', error);
                            ElMessage.error('查询异常，请重试');
                            allTableData.value = [];
                            paginatedData.value = [];
                            total.value = 0;
                        }
                    };

                    loadData();
                };

                const resetForm = () => {
                    transferOrderNoInput.value = '';
                    selectedStatus.value = '';
                    selectedInOutStatus.value = '';
                    dateRange.value = [];
                    if (multipleTable.value) multipleTable.value.clearSelection();
                    currentPage.value = 1;
                    // 重置后重新加载全部数据
                    searchTable();
                };

                // 9. 分页事件
                const handleSizeChange = (val) => {
                    pageSize.value = val;
                    currentPage.value = 1;
                    paginateTableData();
                };

                const handleCurrentChange = (val) => {
                    currentPage.value = val;
                    paginateTableData();
                };

                // 10. 表格选中事件
                const handleSelectionChange = (val) => {
                    
                    selectedRows.value = val;
                    console.log("选中的为:",selectedRows);
                };

                const selectedRowCount = computed(() => {
                    // 校验 selectedRows.value 是数组，避免异常
                    return Array.isArray(selectedRows.value) ? selectedRows.value.length : 0;
                });

                // 11. 核心按钮事件
                const addOrder = () => {
                    window.location.href = '/WhTransfer/AddIndex';
                };

                const deleteOrder = () => {
                    if (!selectedRows.value || selectedRows.value.length === 0) {
                        return ElMessage.warning('请先选中要删除的调拨单');
                    }
                    ElMessageBox.confirm(
                        `确定删除选中的${selectedRows.value.length}条调拨单？删除后不可恢复！`,
                        '确认删除',
                        { type: 'danger' }
                    ).then(async () => {
                        try {
                            const orderIds = selectedRows.value.map(row => row.transferOrderId).join(',');
                            const res = await axios.post('/WhTransfer/DeleteTransferOrders', { orderIds });
                            if (res.data.success || res.data > 0) {
                                ElMessage.success('删除成功');
                                loadTableData();
                            } else {
                                ElMessage.error(`删除失败：${res.data.message || '服务器异常'}`);
                            }
                        } catch (error) {
                            console.error('批量删除失败：', error);
                            ElMessage.error('网络异常，删除请求发送失败');
                        }
                    }).catch(() => {});
                };

                const deleteSingleOrder = (row) => {
                    ElMessageBox.confirm(
                        `确定删除调拨单【${row.transferOrderNo}】？删除后不可恢复！`,
                        '确认删除',
                        { type: 'danger' }
                    ).then(async () => {
                        try {
                            const res = await axios.post('/WhTransfer/DeleteTransferOrders', {
                                orderIds: row.transferOrderId
                            });
                            if (res.data.success || res.data > 0) {
                                ElMessage.success('删除成功');
                                loadTableData();
                            } else {
                                ElMessage.error(`删除失败：${res.data.message || '服务器异常'}`);
                            }
                        } catch (error) {
                            console.error('单个删除失败：', error);
                            ElMessage.error('删除请求异常');
                        }
                    }).catch(() => {});
                };

                const copyOrder = () => {
                    if (selectedRows.value.length !== 1) {
                        return ElMessage.warning('请选中1条调拨单进行复制');
                    }
                    const target = selectedRows.value[0];
                    window.location.href = `/WhTransfer/CopyTransfer?orderId=${target.transferOrderId}`;
                };

                // 打开审核模态框（支持批量+单条）
                const openAuditModal = () => {
                    // 先校验是否为数组，再判断长度
                    if (!Array.isArray(selectedRows.value)) {
                        return ElMessage.warning('请选中至少1条调拨单进行审核');
                    }
                    // 筛选仅“待审核”状态的单据
                    const canAuditRows = selectedRows.value.filter(row => getStatusText(row.orderStatus) === '待审核');
                    if (canAuditRows.length === 0) {
                        return ElMessage.error('选中的单据中无「待审核」状态的订单，请重新选择！');
                    }
                    // 重置模态框数据
                    selectedAuditResult.value = 'pass';
                    auditOpinion.value = '';
                    isAuditModalOpen.value = true;
                };

                // 提交审核（核心：适配后端AuditerModel参数，与进货订单对齐）
                const confirmAudit = async () => {
                    // 1. 基础校验
                    if (!selectedAuditResult.value) {
                        return ElMessage.warning('请选择审核结果（通过/驳回）！');
                    }
                    // 驳回时必填审核意见
                    if (selectedAuditResult.value === 'reject' && !auditOpinion.value.trim()) {
                        return ElMessage.warning('驳回时必须填写审核意见！');
                    }
                    // 校验登录人ID
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }
                    // 筛选可审核行（避免重复筛选）
                    const canAuditRows = selectedRows.value.filter(row => getStatusText(row.orderStatus) === '待审核');

                    // 2. 构造后端需要的AuditerModel参数
                    const auditParam = {
                        IdList: canAuditRows.map(row => Number(row.transferOrderId)), // 转数字类型，与进货订单一致
                        AuditorId: Number(currentUserId.value), // 审核人ID（转数字）
                        AuditorStatu: selectedAuditResult.value === 'pass' ? '4' : '2', // 通过=4，驳回=2（保持原状态码映射）
                        AuditeComment: auditOpinion.value.trim() || ''
                    };

                    try {
                        const res = await axios.post('/WhTransfer/AuditeTransfer', auditParam, {
                            headers: { 'Content-Type': 'application/json' } // 统一请求头格式
                        });
                        if (res.data > 0) {
                            ElMessage.success(`成功审核${res.data}条调拨单`);
                            isAuditModalOpen.value = false;
                            // 刷新表格并清空选中状态
                            if (multipleTable.value) multipleTable.value.clearSelection();
                            selectedRows.value = [];
                            loadTableData();
                        } else {
                            ElMessage.error(`审核失败：${res.data.message || '服务器处理异常'}`);
                        }
                    } catch (error) {
                        console.error('审核请求异常：', error);
                        ElMessage.error('网络异常，审核请求发送失败');
                    }
                };

                const handleAuditModalClose = (done) => {
                    // 重置模态框数据
                    selectedAuditResult.value = '';
                    auditOpinion.value = '';
                    // 调用done()确认关闭模态框
                    done();
                };

                const cancleCheck = () => {
                    // 校验选中数量+登录状态（与进货订单一致）
                    if (!selectedRows.value || selectedRows.value.length !== 1) {
                        return ElMessage.warning('请选中1条调拨单进行撤销');
                    }
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }
                    const target = selectedRows.value[0];
                    const allowStatus = ['已审核', '驳回'];
                    if (!allowStatus.includes(getStatusText(target.orderStatus))) {
                        return ElMessage.warning(`仅${allowStatus.join('、')}的调拨单可撤销，当前状态：${getStatusText(target.orderStatus)}`);
                    }
                    ElMessageBox.confirm(
                        `确定撤销调拨单【${target.transferOrderNo}】的审核状态？撤销后状态将恢复为「待审核」`,
                        '确认撤销',
                        { type: 'warning' }
                    ).then(async () => {
                        try {
                            const res = await axios.post('/WhTransfer/CancelTransferAudit', {
                                orderId: Number(target.transferOrderId), // 转数字类型
                                UserId: Number(currentUserId.value) // 新增撤销人ID参数（与进货订单一致）
                            }, { headers: { 'Content-Type': 'application/json' } });
                            if (res.data.success || res.data > 0) {
                                ElMessage.success('撤销成功，调拨单恢复为待审核');
                                loadTableData();
                                if (multipleTable.value) multipleTable.value.clearSelection();
                                selectedRows.value = [];
                            } else {
                                ElMessage.error(`撤销失败：${res.data.message || '服务器处理异常'}`);
                            }
                        } catch (error) {
                            console.error('撤销请求异常：', error);
                            ElMessage.error('网络异常，无法完成撤销');
                        }
                    }).catch(() => {});
                };

                const exportTable = () => {
                    const params = new URLSearchParams({
                        transferOrderNo: transferOrderNoInput.value.trim() || '',
                        orderStatus: selectedStatus.value || '',
                        inOutStatus: selectedInOutStatus.value || '',
                        startDate: dateRange.value[0] || '',
                        endDate: dateRange.value[1] || ''
                    });
                    window.open(`/WhTransfer/ExportTransferList?${params.toString()}`, '_blank');
                };

                const refrushTable = () => {
                    if (multipleTable.value) multipleTable.value.clearSelection();
                    loadTableData();
                };

                const jumpToDetail = (row) => {
                    window.location.href = `/WhTransfer/TransferDetail?orderId=${row.transferOrderId}`;
                };

                const handleEdit = (row) => {
                    if (!['草稿', '驳回'].includes(getStatusText(row.orderStatus))) {
                        return ElMessage.warning(`仅“草稿”“驳回”的调拨单可编辑，当前状态：${getStatusText(row.orderStatus)}`);
                    }
                    window.location.href = `/WhTransfer/EditTransfer?orderId=${row.transferOrderId}`;
                };

                const handleRejectCancel = (row) => {
                    // 校验登录状态（新增，与进货订单一致）
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }
                    ElMessageBox.confirm(
                        `确定撤销调拨单【${row.transferOrderNo}】的驳回状态？撤销后恢复为待审核`,
                        '确认撤销',
                        { type: 'warning' }
                    ).then(async () => {
                        try {
                            const res = await axios.post('/WhTransfer/CancelTransferReject', {
                                orderId: Number(row.transferOrderId),
                                UserId: Number(currentUserId.value) // 新增撤销人ID参数
                            }, { headers: { 'Content-Type': 'application/json' } });
                            if (res.data.success || res.data > 0) {
                                ElMessage.success('撤销驳回成功，调拨单恢复为待审核');
                                loadTableData();
                            } else {
                                ElMessage.error(`撤销驳回失败：${res.data.message || '服务器处理异常'}`);
                            }
                        } catch (error) {
                            console.error('撤销驳回异常：', error);
                            ElMessage.error('网络异常，无法完成撤销');
                        }
                    }).catch(() => {});
                };

                // 12. 页面初始化
                onMounted(() => {
                    initDictData();
                    nextTick(() => {
                        if (multipleTable.value) {
                            console.log('调拨单表格初始化完成');
                        }
                    });
                });

                // 13. 暴露变量与方法
                return {
                    transferOrderNoInput, selectedStatus, selectedInOutStatus, dateRange, size,
                    paginatedData, currentPage, pageSize, total, multipleTable,
                    stockInStatusList, stockInOutStatusList, transferTypeList,
                    isAuditModalOpen, selectedAuditResult, auditOpinion, currentUserId,
                    formatDate, formatNumber, formatGoodsName,selectedRowCount,
                    formatStatusColumn, formatTransferTypeColumn, formatInOutStatusColumn,
                    getStatusText, getTransferTypeText, getInOutStatusText,
                    searchTable, resetForm, handleSizeChange, handleCurrentChange, handleSelectionChange,
                    addOrder, deleteOrder, deleteSingleOrder, copyOrder, openAuditModal, confirmAudit,
                    handleAuditModalClose, cancleCheck, exportTable, refrushTable,
                    jumpToDetail, handleEdit, handleRejectCancel
                };
            }
        });

        app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
        app.mount('#app');
    </script>
</body>
</html>
